using System.Reflection;
using System.Text;
using Org.Apache.Rocketmq;
using Vin.Extension.RocketMQ.Attributes;
using Vin.Tool.Core.AssertCategory;

namespace Vin.Extension.RocketMQ.Models;

public abstract class VinMessage
{
    public abstract string Topic { get; set; }

    public abstract string Tag { get; set; }

    public virtual string? MessageGroup { get; set; }

    public Message CreateMessage(string body)
    {
        return CreateMessage(this.Topic, this.Tag, body, this.MessageGroup, null);
    }

    public Message CreateMessage(string body, string key)
    {
        return CreateMessage(this.Topic, this.Tag, body, this.MessageGroup, null, key);
    }
    
    public Message CreateMessage(string body, List<string> keys)
    {
        return CreateMessage(this.Topic, this.Tag, body, this.MessageGroup, null, keys.ToArray());
    }

    public Message CreateMessage(string body, DateTime? deliveryTimestamp)
    {
        return CreateMessage(this.Topic, this.Tag, body, this.MessageGroup, deliveryTimestamp);
    }

    public Message CreateMessage(string body, DateTime? deliveryTimestamp, params string[] keys)
    {
        return CreateMessage(this.Topic, this.Tag, body, this.MessageGroup, deliveryTimestamp, keys);
    }

    public Message CreateMessage(string topic, string tag, string body, string? messageGroup,
        DateTime? deliveryTimestamp, params string[] keys)
    {
        var builder = new Message.Builder()
            .SetTopic(topic)
            .SetTag(tag)
            .SetBody(Encoding.UTF8.GetBytes(body));

        if (messageGroup.IsNotNullOrWhiteSpace()) builder.SetMessageGroup(messageGroup);

        if (deliveryTimestamp.HasValue) builder.SetDeliveryTimestamp(deliveryTimestamp.Value);

        if (keys.Length > 0)
        {
            builder.SetKeys(keys);
        }

        return builder.Build();
    }
}